package codeRandomThoughts.Test2461长度为K子数组中的最大和;

import java.util.HashMap;
import java.util.HashSet;

public class Solution {
    public long maximumSubarraySum(int[] nums, int k) {
        //用于记录滑动窗口内是否有重复元素 以及出现的次数
        HashMap<Integer, Integer> hashMap = new HashMap<>();

        //记录最大子数组和
        long min = Long.MIN_VALUE;
        long maxSubSum = min;
        long currSum = 0;

        //滑动窗口左右的边界,都是闭区间
        int begin = 0;
        int end = 0;

        //滑动窗口初始化
        while (end <= k - 1) {
            int tem = nums[end];
            hashMap.put(tem, hashMap.getOrDefault(tem, 0) + 1);
            currSum += nums[end];
            end++;
        }
        //这里end多往后移了一位,减回来
        end--;
        if (hashMap.size() == k) {
            maxSubSum = currSum;
        }

        //开始滑动
        while (end < nums.length - 1) {
            //begin右移
            int beginNum = nums[begin];
            hashMap.put(beginNum, hashMap.getOrDefault(beginNum, 0) - 1);
            if (hashMap.get(beginNum) == 0) {
                hashMap.remove(beginNum);
            }
            currSum -= beginNum;
            begin++;

            //end右移
            end++;
            int endNum = nums[end];
            hashMap.put(endNum, hashMap.getOrDefault(endNum, 0) + 1);
            currSum += endNum;

            //检测是否为合法的子数组 即其中是否有重复元素
            if (hashMap.size() == k) {
                if (currSum > maxSubSum) {
                    maxSubSum = currSum;
                }
            }
        }

        return maxSubSum == min ? 0 : maxSubSum;
    }
}
